<script setup lang="ts">
  import { PropType } from 'vue'
  import { useSaveSpecifyIntegerAndDecimal } from '@/hooks/useNumber'

  defineOptions({
    name: 'OrderCustomFormInput',
  })

  const props = defineProps({
    // 金额时的最大值
    amountMax: {
      type: Number,
      default: () => 999999999,
    },

    // 纯数字时的最大值
    numberMax: {
      type: Number,
      default: () => 999999999,
    },

    // 最大字数
    maxlength: {
      type: Number,
      default: () => 200,
    },

    // 输入框模式：1-纯文本，2-纯数字，3-金额，4-手机号
    mode: {
      type: Number as PropType<1 | 2 | 3 | 4>,
      default: () => 1,
    },

    // 占位文本
    placeholder: {
      type: String,
      default: () => '请输入文本',
    },

    // 后缀显示的文本
    appendText: {
      type: String,
      default: () => '',
    },

    // 禁用状态
    disabled: {
      type: Boolean,
      default: () => false,
    },
  })

  const emits = defineEmits<{
    (e: 'input', value: string): void
  }>()

  // 用于双向绑定
  const value = defineModel<string | number>('modelValue', { default: '' })

  /**
   * 输入事件
   * @param {string} val - 输入的值
   */
  const handleInput = (val: string) => {
    // 纯数字
    if (props.mode === 2) {
      val = val.replace(/[^\d]/g, '')
      if (Number(val) > props.numberMax) {
        val = String(props.numberMax)
      }
    }

    // 金额
    if (props.mode === 3) {
      val = useSaveSpecifyIntegerAndDecimal(val, {
        max: props.amountMax,
      })
    }

    if (props.mode === 4) {
      val = val.replace(/[^\d]/g, '')
      val = val.substring(0, 11)
    }

    value.value = val
    emits('input', val)
  }
</script>

<template>
  <el-input
    v-model.trim="value"
    :placeholder="props.placeholder"
    clearable
    :maxlength="props.maxlength"
    :disabled="props.disabled"
    @input="handleInput"
  >
    <template v-if="props.appendText" #append>
      {{ props.appendText }}
    </template>
  </el-input>
</template>

<style scoped lang="scss">
  :deep(.el-input) {
    width: 100% !important;

    .el-input__wrapper {
      width: 100% !important;
    }
  }
</style>
